package com.my.mycommonsecurity.utils;

import com.my.mycommoncore.utils.ServletUtil;
import com.my.mycommondomain.constants.SecurityConstants;
import com.my.mycommondomain.constants.TokenConstants;
import jakarta.servlet.Servlet;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;

public class SecurityUtil {


    /**
     * 获取令牌
     * @return 令牌
     */
    public static String getToken(){
        return getToken(ServletUtil.getRequest());
    }
    /**
     * 获取令牌
     * @param request 请求
     * @return 令牌
     */
    public static String getToken(HttpServletRequest request){
        String token = request.getHeader(SecurityConstants.AUTHENTICATION);
        return replaceTokenPrefix(token);
    }

    /**
     * 去掉token前缀
     * @param token 令牌
     * @return token
     */
    public static String replaceTokenPrefix(String token){
        if(StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX)){
            token = token.replaceFirst(TokenConstants.PREFIX, "");

        }
        return token;
    }
}
